package flex.cc.drive.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.drive.dao.DriverInterfaceLogDao;
import flex.cc.drive.dao.DriverSynStatusDao;
import flex.cc.drive.dao.OrderDriverDao;
import flex.cc.drive.dto.DriverInterfaceLogEntity;
import flex.cc.drive.dto.DriverRemarkEntity;
import flex.cc.drive.dto.DriverSynStatusEntity;
import flex.cc.drive.dto.OrderDriverEntity;
import flex.cc.drive.service.DriverRemarkService;
import flex.cc.drive.service.DriverSynStatusService;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;

/**
*
* @author R
* 2022年01月14日 13:35:01
* @desc 代驾单状态同步实现层
*/
@Service("driverSynStatusService")
@Transactional(rollbackFor = Exception.class)
public class DriverSynStatusServiceImpl implements DriverSynStatusService {
    private static final Logger logger = LoggerFactory.getLogger(DriverSynStatusServiceImpl.class);
    
//    @Value("${redeemcode.source}")
//    private String source;
    @Autowired
    private DriverVerifyService driverVerifyService;
    @Autowired
    private OrderDriverDao orderDriverDao;
    @Autowired
    private DriverInterfaceLogDao driverInterfaceLogDao;
    @Autowired
    private DriverRemarkService remarkService;
    @Autowired
    private DriverSynStatusDao driverSynStatusDao;
    @Autowired
    private DriverSmsService driverSmsService;
    @Autowired
    private StoreCouponDao storeCouponDao;
    
	@Override
	public JSONObject driverSynStatus(Map<String, Object> requestBodyMap,String requestJson) {
		JSONObject jsonResult = new JSONObject();
		try {
			//预约编号
			String besCode = (String) requestBodyMap.get("besCode");
			if(PublicUtil.isEmpty(besCode)) {
	    		logger.error("预约编号不能为空");
	    		jsonResult.put("resultCode", "ERROR");
	    		jsonResult.put("resultDesc", "预约编号不能为空");
	            return jsonResult;
			}
			//状态
			String status = (String) requestBodyMap.get("status");
			if(PublicUtil.isEmpty(status)) {
	    		logger.error("状态不能为空");
	    		jsonResult.put("resultCode", "ERROR");
	    		jsonResult.put("resultDesc", "状态不能为空");
	            return jsonResult;
			}
			
			//订单编号
			String orderId = (String) requestBodyMap.get("orderId");
			if(PublicUtil.isEmpty(orderId)) {
	    		logger.error("订单编号不能为空");
	    		jsonResult.put("resultCode", "ERROR");
	    		jsonResult.put("resultDesc", "订单编号不能为空");
	            return jsonResult;
			}
			//第三方订单号
			String outTradeNo = (String) requestBodyMap.get("outTradeNo");
			//实际费用
			String actualAmount = (String) requestBodyMap.get("actualAmount");
			//实际公里数
			String actualKm = (String) requestBodyMap.get("actualKm");
			//目的地
			String destination = (String) requestBodyMap.get("destination");
			//取消人
			String canceller = (String) requestBodyMap.get("canceller");
			//取消原因
			String cancelReason = (String) requestBodyMap.get("cancelReason");
			//备注
			String remark = (String) requestBodyMap.get("remark");
			
			//根据卡券编码 获取卡券信息
			StoreCouponEntity storeCouponEntity = storeCouponDao.queryByCouponNum(orderId);
			//获取卡券对应的渠道商   渠道商不同 请求不同的核销
			String channel = storeCouponEntity.getChannel();
			
			//阳光卡券预约信息查询
			OrderDriverEntity orderDriverEntity = orderDriverDao.findByOrderId(orderId);
			//预约编码
			String orderNo = orderDriverEntity.getOrderNo();
			//卡券编码
			String couponNum = orderId;
			//服务包编码
			String packageCode = orderDriverEntity.getPackageCode();
			//客户电话
			String customerPhone = orderDriverEntity.getTel();
		
			
			//新增预约状态同步信息
			String synStatusDataId = UUID.randomUUID().toString().replace("-", "");
			DriverSynStatusEntity driverSynStatusEntity = new DriverSynStatusEntity();
			driverSynStatusEntity.setDataId(synStatusDataId);
			driverSynStatusEntity.setOrderNo(orderNo);
			driverSynStatusEntity.setOrderId(orderId);
			driverSynStatusEntity.setBesCode(besCode);
			driverSynStatusEntity.setSource(channel);
			driverSynStatusEntity.setStatus(status);
			driverSynStatusEntity.setOutTradeNo(outTradeNo);
			driverSynStatusEntity.setActualAmount(actualAmount);
			driverSynStatusEntity.setActualKm(actualKm);
			driverSynStatusEntity.setDestination(destination);
			driverSynStatusEntity.setCanceller(canceller);
			driverSynStatusEntity.setCancelReason(cancelReason);
			driverSynStatusEntity.setRemark(remark);
			
			//预约单状态
			String driverOrderStatus = "";
			String driverOrderStatusString = "";
			if(status.equals("1")){//派单成功
				//司机姓名
				String driverName = (String) requestBodyMap.get("driverName");
				//司机电话
				String driverPhone = (String) requestBodyMap.get("driverPhone");
				//司机车牌	
				String carNo = (String) requestBodyMap.get("carNo");
				//车型	
				String vehicleModel = (String) requestBodyMap.get("vehicleModel");
				
				driverSynStatusEntity.setDriverName(driverName);
				driverSynStatusEntity.setDriverPhone(driverPhone);
				driverSynStatusEntity.setCarNo(carNo);
				driverSynStatusEntity.setVehicleModel(vehicleModel);
				
				driverOrderStatusString = "派单成功";
				driverOrderStatus = "02";
				
				//调用短信接口
				Map<String, String> params = new HashMap<String, String>();
				params.put("driverStatus", "001");
				params.put("phoneNumber", customerPhone);
				params.put("driverName", driverName);
				params.put("driverPhone", driverPhone);
				driverSmsService.sendDriverSms(params);
			}else if(status.equals("2")){//服务完成
				driverOrderStatusString = "服务完成";
				driverOrderStatus = "04";
				
				Map<String, String> postMap = new HashMap<String, String>();
				postMap.put("orderNo", orderNo);
				postMap.put("couponNum", couponNum);
				postMap.put("packageCode", packageCode);
				//调用核销接口
				driverVerifyService.verifyNotice(postMap);
			}else if(status.equals("5")){//取消可用服务 
				driverOrderStatusString = "取消可用服务";
				driverOrderStatus = "05";
			}else if(status.equals("6")){//司机已到达
				// 需查询数据库 该服务单 派单成功时 司机电话和司机姓名
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("status", "1");
				params.put("orderNo", orderNo);
				DriverSynStatusEntity driverSynStatusInfo = driverSynStatusDao.getOneByParams(params);
				String driverPhone = driverSynStatusInfo.getDriverPhone();
				String driverName = driverSynStatusInfo.getDriverName();
				
				//调用短信接口
				Map<String, String> smsParams = new HashMap<String, String>();
				smsParams.put("driverStatus", "002");
				smsParams.put("phoneNumber", customerPhone);
				smsParams.put("driverName", driverName);
				smsParams.put("driverPhone", driverPhone);
				driverSmsService.sendDriverSms(smsParams);
				
				driverOrderStatusString = "司机已到达";
				driverOrderStatus = "03";
			}else if(status.equals("8")){//取消服务完成
				driverOrderStatusString = "取消服务完成";
				driverOrderStatus = "06";
				
				Map<String, String> postMap = new HashMap<String, String>();
				postMap.put("orderNo", orderNo);
				postMap.put("couponNum", couponNum);
				postMap.put("packageCode", packageCode);
				//调用核销接口
				driverVerifyService.verifyNotice(postMap);
			}else if(status.equals("9")){//预约成功	
				driverOrderStatusString = "预约成功";
				driverOrderStatus = "01";
			}else {//其他 不更新代驾服务单状态 只记录轨迹
				driverOrderStatusString = "其他";
			}
			//插入同步状态数据
			driverSynStatusEntity.setCreateTime(new Date());
			driverSynStatusEntity.setCreater("system");
			driverSynStatusEntity.setUpdateTime(new Date());
			driverSynStatusEntity.setUpdater("system");
			driverSynStatusEntity.setIsDelete(0);
			driverSynStatusDao.insert(driverSynStatusEntity);
			
			if(PublicUtil.isNotEmpty(driverOrderStatus)){
				//按照状态同步接口返回的状态更新预约服务单
				Map<String, Object> orderParam = new HashMap<String, Object>();
				orderParam.put("status", driverOrderStatus);
				orderParam.put("orderNo", orderNo);
				orderDriverDao.updateByParams(orderParam);
			}
			
			jsonResult.put("resultCode", "SUCCESS");
    		jsonResult.put("resultDesc", "成功,系统处理正常");
			
    		//接口日志新增
    		String logDataId = UUID.randomUUID().toString().replace("-", "");
	    	DriverInterfaceLogEntity driverInterfaceLogEntity = new DriverInterfaceLogEntity();
	    	driverInterfaceLogEntity.setDataId(logDataId);
	    	driverInterfaceLogEntity.setOrderNo(orderNo);
	    	driverInterfaceLogEntity.setOrderId(orderId);
	    	driverInterfaceLogEntity.setInterfaceName("预约单状态同步接口");
	    	JSONObject jsonObj=new JSONObject(requestBodyMap);
	    	driverInterfaceLogEntity.setRequestTime(new Date());
	    	driverInterfaceLogEntity.setRequestBody(jsonObj.toString());
	    	driverInterfaceLogEntity.setResponseBody(jsonResult.toString());
	    	driverInterfaceLogEntity.setResponseTime(new Date());
	    	driverInterfaceLogEntity.setCreateTime(new Date());
	    	driverInterfaceLogDao.insert(driverInterfaceLogEntity);
	    	
	    	String remarkDataId = UUID.randomUUID().toString().replace("-", "");
	    	DriverRemarkEntity driverRemarkEntity = new DriverRemarkEntity();
	    	driverRemarkEntity.setDataId(remarkDataId);
	    	driverRemarkEntity.setOrderNo(orderNo);
	    	driverRemarkEntity.setOrderId(orderId);
	    	driverRemarkEntity.setStatus("0");
	    	driverRemarkEntity.setLink("预约单状态同步，状态："+driverOrderStatusString);
	    	driverRemarkEntity.setRemark("预约单状态同步成功");
	    	driverRemarkEntity.setCreateTime(new Date());
	    	driverRemarkEntity.setCreator("system");
	    	driverRemarkEntity.setUpdateTime(new Date());
	    	driverRemarkEntity.setUpdater("system");
	    	driverRemarkEntity.setIsDelete(0);
	    	remarkService.insert(driverRemarkEntity);
	    	
	    	return jsonResult;
		}catch (Exception e) {
			logger.info("预约单状态同步接口异常"+e.getMessage());
			jsonResult.put("resultCode", "ERROR");
    		jsonResult.put("resultDesc", "预约单状态同步接口异常");
            return jsonResult;
		}
	}
}
